{
  "name": "Case 52: Proof of Delivery Digitizer - Intelligent Agent",
  "nodes": [
    {
      "parameters": {
        "path": "pod-upload-form",
        "formTitle": "Proof of Delivery (PoD) Upload",
        "formDescription": "Upload signed PoD document for automated processing and invoice generation",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Upload PoD Document (Photo/PDF)",
              "fieldType": "file",
              "requiredField": true
            },
            {
              "fieldLabel": "Driver Name",
              "requiredField": true
            },
            {
              "fieldLabel": "Vehicle Number",
              "requiredField": true
            },
            {
              "fieldLabel": "Delivery Completion Time",
              "requiredField": true
            }
          ]
        },
        "options": {}
      },
      "id": "6ec4affc-6ae0-4efc-ba47-6d12a7f5b426",
      "name": "PoD Upload Form",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.1,
      "position": [
        -1488,
        0
      ],
      "webhookId": "pod-upload-form"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cloud.llamaindex.ai/api/v1/parsing/upload",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "parameterType": "formBinaryData",
              "name": "file",
              "inputDataFieldName": "Upload_PoD_Document__Photo_PDF_"
            }
          ]
        },
        "options": {}
      },
      "id": "ef343e3a-1910-4362-9344-275035f3da85",
      "name": "Upload PoD to Parser",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -1280,
        0
      ]
    },
    {
      "parameters": {
        "amount": 20
      },
      "id": "7b2ec40b-bcb8-480a-8bca-0c0ea3377726",
      "name": "Wait for PoD Parsing",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        -1088,
        0
      ],
      "webhookId": "796d73d1-251f-4ada-826c-76733d5af22c"
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload PoD to Parser\"].json[\"id\"] }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "49a8e9c5-f4f7-40c3-962a-25db594b4c16",
      "name": "Check Parsing Status",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -880,
        0
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "SUCCESS",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "SUCCESS"
            },
            {
              "conditions": {
                "conditions": [
                  {
                    "leftValue": "={{ $json.status }}",
                    "rightValue": "PENDING",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ]
              },
              "renameOutput": true,
              "outputKey": "PENDING"
            }
          ]
        },
        "options": {}
      },
      "id": "d403c341-8586-40f3-af64-fc3e315f854c",
      "name": "Status Router",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        -688,
        0
      ]
    },
    {
      "parameters": {
        "url": "=https://api.cloud.llamaindex.ai/api/v1/parsing/job/{{ $node[\"Upload PoD to Parser\"].json[\"id\"] }}/result/markdown",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer llx-7BWYrvPwfUhgdXbZMtaNCsr2O0h7JH4dkHjHisxcvq46bkIj"
            }
          ]
        },
        "options": {}
      },
      "id": "ea7c8583-a472-4762-8adb-a6e6349fdaed",
      "name": "Get Parsed PoD Data",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -480,
        -96
      ]
    },
    {
      "parameters": {
        "text": "={{ $json.markdown }}",
        "attributes": {
          "attributes": [
            {
              "name": "PoD_Number",
              "description": "Unique PoD reference number"
            },
            {
              "name": "Delivery_Date",
              "description": "Actual delivery date in YYYY-MM-DD format"
            },
            {
              "name": "Delivery_Time_Actual",
              "description": "Actual delivery completion time in HH:MM format"
            },
            {
              "name": "Customer_Name",
              "description": "Full customer company name"
            },
            {
              "name": "Customer_Code",
              "description": "Customer reference code"
            },
            {
              "name": "Delivery_Address",
              "description": "Complete delivery address"
            },
            {
              "name": "Contact_Person",
              "description": "Name of person who received delivery"
            },
            {
              "name": "Sales_Order_Number",
              "description": "Original sales order reference"
            },
            {
              "name": "Order_Date",
              "description": "Original order date in YYYY-MM-DD"
            },
            {
              "name": "Scheduled_Delivery_Time",
              "description": "Scheduled delivery time window"
            },
            {
              "name": "Total_Items_Ordered",
              "description": "Total quantity of all items ordered (numeric only)"
            },
            {
              "name": "Total_Items_Delivered",
              "description": "Total quantity of all items actually delivered (numeric only)"
            },
            {
              "name": "Delivery_Completeness_Percentage",
              "description": "Percentage of items delivered: (Delivered/Ordered)*100, rounded to 2 decimals"
            },
            {
              "name": "Delivery_Status",
              "description": "COMPLETE / PARTIAL / DAMAGED / REJECTED"
            },
            {
              "name": "Shortage_Details",
              "description": "Details of any missing items with quantities, or NONE"
            },
            {
              "name": "Timeliness_Status",
              "description": "ON_TIME / EARLY / LATE_MINOR / LATE_MAJOR"
            },
            {
              "name": "Delay_Hours",
              "description": "Number of hours late (negative if early, 0 if on-time)"
            },
            {
              "name": "Quality_Issues",
              "description": "Description of any damages/quality problems, or NONE"
            },
            {
              "name": "Packaging_Condition",
              "description": "Condition of packaging: INTACT / DAMAGED / TAMPERED"
            },
            {
              "name": "Signature_Present",
              "description": "YES / NO"
            },
            {
              "name": "Signature_Clarity",
              "description": "CLEAR / UNCLEAR / MISSING"
            },
            {
              "name": "Receiver_Name",
              "description": "Name of person who signed PoD"
            },
            {
              "name": "Receiver_Designation",
              "description": "Job title of receiver"
            },
            {
              "name": "Company_Stamp_Present",
              "description": "YES / NO"
            },
            {
              "name": "Full_Order_Amount",
              "description": "Total order value in numeric format (no currency symbols)"
            },
            {
              "name": "Delivered_Amount",
              "description": "Value of delivered items only (numeric)"
            },
            {
              "name": "Amount_On_Hold",
              "description": "Amount held for pending/missing items (numeric)"
            },
            {
              "name": "Payment_Terms",
              "description": "Payment terms mentioned (e.g., Net 30 days)"
            },
            {
              "name": "Backorder_Required",
              "description": "YES / NO"
            },
            {
              "name": "Backorder_Items",
              "description": "Details of items to be backordered, or NONE"
            },
            {
              "name": "Next_Delivery_Date",
              "description": "Scheduled date for backorder delivery in YYYY-MM-DD, or NOT_SCHEDULED"
            },
            {
              "name": "Customer_Comments",
              "description": "Any comments or notes from customer"
            },
            {
              "name": "Driver_Name",
              "description": "Name of delivery driver"
            },
            {
              "name": "Vehicle_Number",
              "description": "Vehicle registration number"
            }
          ]
        },
        "options": {}
      },
      "id": "a7c85bb6-d720-41c2-b5d9-a11bcef11990",
      "name": "Extract PoD Intelligence",
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        -240,
        -96
      ]
    },
    {
      "parameters": {
        "jsCode": "const extracted = $node[\"Extract PoD Intelligence\"].json.output;\nconst formData = $node[\"PoD Upload Form\"].json;\n\n// ===== DELIVERY SCORING ENGINE =====\n\nlet deliveryScore = 0;\n\n// 1. COMPLETENESS SCORE (40 points max)\nconst completeness = parseFloat(extracted.Delivery_Completeness_Percentage);\nif (completeness === 100) {\n  deliveryScore += 40;\n} else if (completeness >= 95) {\n  deliveryScore += 35;\n} else if (completeness >= 90) {\n  deliveryScore += 30;\n} else if (completeness >= 75) {\n  deliveryScore += 20;\n} else {\n  deliveryScore += 10;\n}\n\n// 2. TIMELINESS SCORE (30 points max)\nconst timeliness = extracted.Timeliness_Status.toUpperCase();\nif (timeliness.includes('ON_TIME') || timeliness.includes('EARLY')) {\n  deliveryScore += 30;\n} else if (timeliness.includes('LATE_MINOR')) {\n  deliveryScore += 20;\n} else if (timeliness.includes('LATE_MAJOR')) {\n  deliveryScore += 10;\n} else {\n  deliveryScore += 5;\n}\n\n// 3. QUALITY SCORE (20 points max)\nconst qualityIssues = extracted.Quality_Issues.toUpperCase();\nif (qualityIssues === 'NONE' || qualityIssues === 'NOT_FOUND') {\n  deliveryScore += 20;\n} else if (qualityIssues.includes('MINOR')) {\n  deliveryScore += 10;\n} else {\n  deliveryScore += 0;\n}\n\n// 4. DOCUMENTATION SCORE (10 points max)\nlet docScore = 0;\nif (extracted.Signature_Present === 'YES') {\n  docScore += 5;\n}\nif (extracted.Signature_Clarity === 'CLEAR') {\n  docScore += 3;\n}\nif (extracted.Company_Stamp_Present === 'YES') {\n  docScore += 2;\n}\ndeliveryScore += docScore;\n\n// ===== INVOICE ACTION DETERMINATION =====\n\nlet invoiceAction = '';\nlet invoiceAmount = 0;\nlet nextAction = '';\n\nconst deliveryStatus = extracted.Delivery_Status.toUpperCase();\nconst signaturePresent = extracted.Signature_Present === 'YES';\nconst hasQualityIssues = qualityIssues !== 'NONE' && qualityIssues !== 'NOT_FOUND';\n\nif (deliveryScore >= 90 && deliveryStatus === 'COMPLETE' && signaturePresent) {\n  invoiceAction = 'GENERATE_FULL_INVOICE';\n  invoiceAmount = parseFloat(extracted.Full_Order_Amount || 0);\n  nextAction = 'Auto-generate invoice and update ERP. Send invoice to customer.';\n} else if (deliveryScore >= 70 && deliveryStatus === 'PARTIAL' && signaturePresent) {\n  invoiceAction = 'GENERATE_PARTIAL_INVOICE';\n  invoiceAmount = parseFloat(extracted.Delivered_Amount || 0);\n  nextAction = `Generate partial invoice for delivered items. Create backorder for ${extracted.Backorder_Items}. Schedule follow-up delivery.`;\n} else if (hasQualityIssues || deliveryStatus === 'DAMAGED') {\n  invoiceAction = 'HOLD_INVOICE_QUALITY_ISSUE';\n  invoiceAmount = 0;\n  nextAction = 'Hold invoice pending quality inspection. Notify logistics manager and customer service for resolution.';\n} else if (deliveryStatus === 'REJECTED' || !signaturePresent) {\n  invoiceAction = 'BLOCK_INVOICE_NO_ACCEPTANCE';\n  invoiceAmount = 0;\n  nextAction = 'Block invoice - delivery not accepted. Initiate investigation and arrange return/redelivery.';\n} else {\n  invoiceAction = 'REVIEW_REQUIRED';\n  invoiceAmount = 0;\n  nextAction = 'Manual review required. Alert logistics manager for decision.';\n}\n\n// ===== BACKORDER LOGIC =====\n\nconst backorderRequired = extracted.Backorder_Required === 'YES' || completeness < 100;\nconst backorderDetails = backorderRequired ? extracted.Backorder_Items : 'NONE';\n\n// ===== GENERATE UNIQUE TRACKING ID =====\n\nconst timestamp = new Date().toISOString().replace(/[-:]/g, '').split('.')[0];\nconst podId = extracted.PoD_Number || `POD-AUTO-${timestamp}`;\n\n// ===== RETURN STRUCTURED DATA FOR GOOGLE SHEETS =====\n\nreturn {\n  PoD_Number: podId,\n  Delivery_Date: extracted.Delivery_Date,\n  Customer_Name: extracted.Customer_Name,\n  Order_Number: extracted.Sales_Order_Number,\n  Items_Ordered: extracted.Total_Items_Ordered,\n  Items_Delivered: extracted.Total_Items_Delivered,\n  Delivery_Completeness_Percentage: `${completeness}%`,\n  Delivery_Status: deliveryStatus,\n  Timeliness_Status: timeliness,\n  Quality_Issues: qualityIssues,\n  Delivery_Score: deliveryScore,\n  Invoice_Action: invoiceAction,\n  Invoice_Amount: `₹${invoiceAmount.toFixed(2)}`,\n  Backorder_Required: backorderRequired ? 'YES' : 'NO',\n  Next_Action: nextAction,\n  \n  // Pass through for email and ERP\n  _full_pod_data: extracted,\n  _form_data: formData,\n  _invoice_amount_numeric: invoiceAmount,\n  _backorder_details: backorderDetails\n};"
      },
      "id": "f9f4081a-b443-4f32-bb84-42dc1a6ed223",
      "name": "Delivery Validation Engine",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        64,
        -96
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "15cBHBeHtLapHZWW7iw2PppnLj72RMoWLHxaZMMBR3iI",
          "mode": "list",
          "cachedResultName": "Case 52 - POD Folder",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15cBHBeHtLapHZWW7iw2PppnLj72RMoWLHxaZMMBR3iI/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/15cBHBeHtLapHZWW7iw2PppnLj72RMoWLHxaZMMBR3iI/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "PoD_Number": "={{ $json.PoD_Number }}",
            "Delivery_Date": "={{ $json.Delivery_Date }}",
            "Customer_Name": "={{ $json.Customer_Name }}",
            "Order_Number": "={{ $json.Order_Number }}",
            "Items_Ordered": "={{ $json.Items_Ordered }}",
            "Items_Delivered": "={{ $json.Items_Delivered }}",
            "Delivery_Completeness_%": "={{ $json.Delivery_Completeness_Percentage }}",
            "Delivery_Status": "={{ $json.Delivery_Status }}",
            "Timeliness_Status": "={{ $json.Timeliness_Status }}",
            "Quality_Issues": "={{ $json.Quality_Issues }}",
            "Delivery_Score": "={{ $json.Delivery_Score }}",
            "Invoice_Action": "={{ $json.Invoice_Action }}",
            "Invoice_Amount": "={{ $json.Invoice_Amount }}",
            "Backorder_Required": "={{ $json.Backorder_Required }}",
            "Next_Action": "={{ $json.Next_Action }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "PoD_Number",
              "displayName": "PoD_Number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Delivery_Date",
              "displayName": "Delivery_Date",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Customer_Name",
              "displayName": "Customer_Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Order_Number",
              "displayName": "Order_Number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Items_Ordered",
              "displayName": "Items_Ordered",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Items_Delivered",
              "displayName": "Items_Delivered",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Delivery_Completeness_%",
              "displayName": "Delivery_Completeness_%",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Delivery_Status",
              "displayName": "Delivery_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Timeliness_Status",
              "displayName": "Timeliness_Status",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Quality_Issues",
              "displayName": "Quality_Issues",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Delivery_Score",
              "displayName": "Delivery_Score",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Invoice_Action",
              "displayName": "Invoice_Action",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Invoice_Amount",
              "displayName": "Invoice_Amount",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Backorder_Required",
              "displayName": "Backorder_Required",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Next_Action",
              "displayName": "Next_Action",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "8fafb6b4-e999-4fbd-8cd4-f39cebc9c130",
      "name": "Log to Delivery Database",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        272,
        -96
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "LOs2dbk9lby0NfDM",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.Invoice_Action }}",
                    "rightValue": "GENERATE_FULL_INVOICE",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "9f182243-d4d4-4a02-a8bf-dae12bb49c57"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "AUTO_INVOICE"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.Invoice_Action }}",
                    "rightValue": "GENERATE_PARTIAL_INVOICE",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "c07bfb3e-d42e-4a4f-9de0-98f98f177668"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "AUTO_INVOICE"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.Invoice_Action }}",
                    "rightValue": "HOLD_INVOICE_QUALITY_ISSUE",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    },
                    "id": "d2d66679-d775-4200-bd23-14056fd5f3f6"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "ALERT_MANAGER"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.Invoice_Action }}",
                    "rightValue": "BLOCK_INVOICE",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    },
                    "id": "b5112557-65ea-4040-9493-5ba7d675a79e"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "ALERT_MANAGER"
            }
          ]
        },
        "options": {
          "fallbackOutput": "none"
        }
      },
      "id": "2b7adf1e-5f95-46f0-b1a7-884fdd6d0c02",
      "name": "Invoice Action Router",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        512,
        -96
      ]
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst pod = data._full_pod_data || {};\n\n// Simulate ERP Update\nconst erpPayload = {\n  action: 'UPDATE_DELIVERY_AND_INVOICE',\n  pod_number: data.PoD_Number,\n  sales_order: data.Order_Number,\n  customer_code: pod.Customer_Code,\n  delivery_status: data.Delivery_Status,\n  invoice_action: data.Invoice_Action,\n  invoice_amount: data._invoice_amount_numeric,\n  items_delivered: data.Items_Delivered,\n  backorder_required: data.Backorder_Required === 'YES',\n  backorder_items: data._backorder_details,\n  timestamp: new Date().toISOString()\n};\n\nreturn {\n  erp_update_status: 'SUCCESS',\n  erp_payload: JSON.stringify(erpPayload, null, 2),\n  invoice_generated: data.Invoice_Action.includes('GENERATE'),\n  message: `ERP updated successfully. ${data.Invoice_Action.replace(/_/g, ' ')}.`,\n  ...data\n};"
      },
      "id": "d6bc6ffe-3739-4f12-af69-60f1f53acc55",
      "name": "Update ERP System",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        768,
        -208
      ]
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst pod = data._full_pod_data || {};\n\nconst emailSubject = `✅ Delivery Complete - Invoice ${data.Invoice_Action.includes('FULL') ? 'Generated' : 'Processed'} | ${data.PoD_Number}`;\n\nconst emailBody = `\n<html>\n<body style=\"font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 700px; margin: 0 auto; padding: 20px;\">\n<div style=\"background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 25px; border-radius: 8px; margin-bottom: 20px;\">\n<h1 style=\"margin: 0; font-size: 24px;\">✅ Delivery Processed Successfully</h1>\n<p style=\"margin: 5px 0 0 0; opacity: 0.95;\">PoD: ${data.PoD_Number}</p>\n</div>\n\n<div style=\"background: #ecfdf5; border-left: 4px solid #10b981; padding: 15px; margin: 20px 0; border-radius: 4px;\">\n<strong>Invoice ${data.Invoice_Action.includes('FULL') ? 'Generated and Sent' : 'Processed'}</strong><br>\nERP system has been updated automatically. ${data.Invoice_Action.includes('FULL') ? 'Full invoice sent to customer.' : 'Partial invoice generated for delivered items.'}\n</div>\n\n<div style=\"background: #f9fafb; padding: 20px; border-radius: 8px; margin: 20px 0;\">\n<h2 style=\"margin: 0 0 15px 0; font-size: 18px; color: #111827; border-bottom: 2px solid #e5e7eb; padding-bottom: 10px;\">📋 Delivery Summary</h2>\n<table style=\"width: 100%; border-collapse: collapse;\">\n<tr><td style=\"padding: 8px 0; color: #6b7280; font-weight: 600;\">Customer:</td><td style=\"padding: 8px 0; font-weight: 600;\">${data.Customer_Name}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280; font-weight: 600;\">Order Number:</td><td style=\"padding: 8px 0;\">${data.Order_Number}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280; font-weight: 600;\">Delivery Date:</td><td style=\"padding: 8px 0;\">${data.Delivery_Date}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280; font-weight: 600;\">Items Delivered:</td><td style=\"padding: 8px 0;\"><strong>${data.Items_Delivered} / ${data.Items_Ordered}</strong> (${data.Delivery_Completeness_Percentage})</td></tr>\n<tr><td style=\"padding: 8px 0 ; color: #6b7280; font-weight: 600;\">Delivery Score:</td><td style=\"padding: 8px 0;\"><strong style=\"color: #10b981; font-size: 20px;\">${data.Delivery_Score}/100</strong></td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280; font-weight: 600;\">Invoice Amount:</td><td style=\"padding: 8px 0; font-size: 18px; color: #10b981; font-weight: 700;\">${data.Invoice_Amount}</td></tr>\n</table>\n</div>\n\n${data.Backorder_Required === 'YES' ? `\n<div style=\"background: #fef3c7; border: 2px solid #f59e0b; border-radius: 8px; padding: 15px; margin: 20px 0;\">\n<h3 style=\"margin: 0 0 10px 0; color: #92400e; font-size: 16px;\">⚠️ Backorder Required</h3>\n<p style=\"margin: 5px 0;\"><strong>Items:</strong> ${data._backorder_details}</p>\n<p style=\\\"margin: 5px 0;\\\"><strong>Next Delivery:</strong> ${pod.Next_Delivery_Date || 'Not scheduled'}</p>\n</div>\n` : ''}\n\n<div style=\"background: #eff6ff; border: 2px solid #3b82f6; border-radius: 8px; padding: 20px; margin: 20px 0;\">\n<h3 style=\"margin: 0 0 15px 0; color: #1e40af; font-size: 16px;\">📋 Next Actions</h3>\n<p style=\"margin: 0;\">${data.Next_Action}</p>\n</div>\n\n<div style=\"background: #f9fafb; padding: 15px; text-align: center; margin-top: 30px; border-top: 2px solid #e5e7eb; font-size: 13px; color: #6b7280;\">\n<p style=\"margin: 0;\"><strong>Automated PoD Processing System</strong></p>\n<p style=\"margin: 5px 0 0 0;\">Generated: ${new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' })}</p>\n</div>\n</body>\n</html>\n`;\n\nreturn {\n  emailSubject: emailSubject,\n  emailBody: emailBody,\n  recipientEmail: pod.Contact_Person ? `${pod.Contact_Person.toLowerCase().replace(/ /g, '.')}@company.com` : 'accounts@company.com'\n};"
      },
      "id": "9826cc49-b5e8-4057-9cea-0bf168c54647",
      "name": "Build Success Email",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1024,
        -208
      ]
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst pod = data._full_pod_data || {};\n\nconst emailSubject = `🚨 URGENT: Delivery Issue - Manual Review Required | ${data.PoD_Number}`;\n\nconst emailBody = `\n<html>\n<body style=\"font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 700px; margin: 0 auto; padding: 20px;\">\n<div style=\"background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%); color: white; padding: 25px; border-radius: 8px; margin-bottom: 20px;\">\n<h1 style=\"margin: 0; font-size: 24px;\">🚨 Delivery Issue Detected</h1>\n<p style=\"margin: 5px 0 0 0; opacity: 0.95;\">PoD: ${data.PoD_Number} | Action: ${data.Invoice_Action}</p>\n</div>\n\n<div style=\"background: #fee2e2; border-left: 4px solid #dc2626; padding: 15px; margin: 20px 0; border-radius: 4px;\">\n<strong>⚠️ MANUAL REVIEW REQUIRED</strong><br>\nDelivery could not be auto-processed. Immediate attention needed from logistics manager.\n</div>\n\n<div style=\"background: #f9fafb; padding: 20px; border-radius: 8px; margin: 20px 0;\">\n<h2 style=\"margin: 0 0 15px 0; font-size: 18px; color: #111827;\">📋 Delivery Details</h2>\n<table style=\"width: 100%;\">\n<tr><td style=\"padding: 8px 0; color: #6b7280;\">Customer:</td><td style=\"padding: 8px 0; font-weight: 600;\">${data.Customer_Name}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280;\">Order:</td><td style=\"padding: 8px 0;\">${data.Order_Number}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280;\">Delivery Score:</td><td style=\"padding: 8px 0; color: #dc2626; font-weight: 700; font-size: 20px;\">${data.Delivery_Score}/100</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280;\">Status:</td><td style=\"padding: 8px 0; color: #dc2626; font-weight: 700;\">${data.Delivery_Status}</td></tr>\n<tr><td style=\"padding: 8px 0; color: #6b7280;\">Quality Issues:</td><td style=\"padding: 8px 0; color: #dc2626;\">${data.Quality_Issues}</td></tr>\n</table>\n</div>\n\n<div style=\"background: #eff6ff; border: 2px solid #3b82f6; border-radius: 8px; padding: 20px; margin: 20px 0;\">\n<h3 style=\"margin: 0 0 15px 0; color: #1e40af;\">📋 Required Actions</h3>\n<p style=\"margin: 0;\">${data.Next_Action}</p>\n</div>\n\n<div style=\"text-align: center; margin: 25px 0;\">\n<a href=\"https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID\" style=\"display: inline-block; background: #3b82f6; color: white; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600;\">📊 View Full PoD Database</a>\n</div>\n\n<div style=\"background: #f9fafb; padding: 15px; text-align: center; margin-top: 30px; border-top: 2px solid #e5e7eb; font-size: 13px; color: #6b7280;\">\n<p style=\"margin: 0;\"><strong>Automated PoD Alert System</strong></p>\n<p style=\"margin: 5px 0 0 0;\">Generated: ${new Date().toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' })}</p>\n</div>\n</body>\n</html>\n`;\n\nreturn {\n  emailSubject: emailSubject,\n  emailBody: emailBody,\n  recipientEmail: 'logistics.manager@company.com'\n};"
      },
      "id": "44926dd3-c7c6-409c-9958-2ff18c7f3625",
      "name": "Build Alert Email",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1024,
        0
      ]
    },
    {
      "parameters": {
        "sendTo": "={{ $json.recipientEmail }}",
        "subject": "={{ $json.emailSubject }}",
        "message": "={{ $json.emailBody }}",
        "options": {}
      },
      "id": "ab187b01-0996-4bcb-ac03-f02fdee37820",
      "name": "Send Invoice Confirmation",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1280,
        -208
      ],
      "webhookId": "f0d5b293-7a00-4b63-bde6-09de8f3e505d",
      "credentials": {
        "gmailOAuth2": {
          "id": "cyqCGWcggZNMcSOv",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "sendTo": "={{ $json.recipientEmail }}",
        "subject": "={{ $json.emailSubject }}",
        "message": "={{ $json.emailBody }}",
        "options": {}
      },
      "id": "20397b0a-ac68-4ea6-b0f6-3bdc105fbf87",
      "name": "Send Manager Alert",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1280,
        0
      ],
      "webhookId": "6373cefd-75db-4881-be96-7eeb0760cbf7",
      "credentials": {
        "gmailOAuth2": {
          "id": "cyqCGWcggZNMcSOv",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list"
        },
        "builtInTools": {},
        "options": {}
      },
      "id": "a497b514-f241-4459-a159-6341ff14b14e",
      "name": "GPT-4o Mini",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        -240,
        96
      ],
      "credentials": {
        "openAiApi": {
          "id": "ICwxUBbatsF2sDvy",
          "name": "OpenAi account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "PoD Upload Form": {
      "main": [
        [
          {
            "node": "Upload PoD to Parser",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload PoD to Parser": {
      "main": [
        [
          {
            "node": "Wait for PoD Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for PoD Parsing": {
      "main": [
        [
          {
            "node": "Check Parsing Status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Parsing Status": {
      "main": [
        [
          {
            "node": "Status Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Status Router": {
      "main": [
        [
          {
            "node": "Get Parsed PoD Data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait for PoD Parsing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Parsed PoD Data": {
      "main": [
        [
          {
            "node": "Extract PoD Intelligence",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract PoD Intelligence": {
      "main": [
        [
          {
            "node": "Delivery Validation Engine",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delivery Validation Engine": {
      "main": [
        [
          {
            "node": "Log to Delivery Database",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Delivery Database": {
      "main": [
        [
          {
            "node": "Invoice Action Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Invoice Action Router": {
      "main": [
        [
          {
            "node": "Update ERP System",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Update ERP System",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Alert Email",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Alert Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update ERP System": {
      "main": [
        [
          {
            "node": "Build Success Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Success Email": {
      "main": [
        [
          {
            "node": "Send Invoice Confirmation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Alert Email": {
      "main": [
        [
          {
            "node": "Send Manager Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4o Mini": {
      "ai_languageModel": [
        [
          {
            "node": "Extract PoD Intelligence",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "71729a6a-0c65-4b1a-9679-6a19797e785c",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "3a43da28588548e21903e71cf1dc3ddd65c24bf0c62e7e4b77542ffe87ad79c6"
  },
  "id": "kHo0GVIdMrOImuB1",
  "tags": []
}